import 'package:casdon/modules/recipe/ui/widgets/Recipe_card_item.dart';
import 'package:tuya_home_sdk_flutter/tuya_home_sdk_flutter.dart';

class RecipeCloudListState {
  final List<DeviceRecipeCloud> data;
  final List<ThingSmartDeviceModel> devList;
  final List<bool> isMiffyList;
  final int pageSize = 20;
  int selectedIndex = 0;

  RecipeCloudListState({
    required this.data,
    required this.devList,
    required this.selectedIndex,
    required this.isMiffyList,
  });

  factory RecipeCloudListState.initial() => RecipeCloudListState(
    data: [],
    devList: [],
    selectedIndex: 0,
    isMiffyList: [],
  );

  RecipeCloudListState copyWith({
    List<DeviceRecipeCloud>? data,
    List<ThingSmartDeviceModel>? devList,
    int? selectedIndex,
    List<bool>? isMiffyList,
  }) {
    return RecipeCloudListState(
      data: data ?? List.from(this.data),
      devList: devList ?? List.from(this.devList),
      selectedIndex: selectedIndex ?? this.selectedIndex,
      isMiffyList: isMiffyList ?? this.isMiffyList,
    );
  }

  RecipeCloudListState merge(RecipeCloudListState other) {
    final Map<String?, DeviceRecipeCloud> deviceCloudMap = {};

    void addClouds(List<DeviceRecipeCloud> clouds) {
      for (final cloud in clouds) {
        final key = cloud.deviceId ?? '${deviceCloudMap.length}';
        deviceCloudMap[key] = cloud;
      }
    }

    addClouds(data);
    addClouds(other.data);

    final Map<String?, ThingSmartDeviceModel> deviceMap = {};
    final Map<String?, bool> miffyMap = {};

    void addDevices(
      List<ThingSmartDeviceModel> devices,
      List<bool> flags,
    ) {
      for (var i = 0; i < devices.length; i++) {
        final device = devices[i];
        final key = device.devId ?? '${deviceMap.length}';
        if (!deviceMap.containsKey(key)) {
          deviceMap[key] = device;
          miffyMap[key] = flags.length > i ? flags[i] : false;
        } else if (flags.length > i && flags[i]) {
          // 如果新的标记为 miffy，则覆盖旧值
          miffyMap[key] = true;
        }
      }
    }

    addDevices(devList, isMiffyList);
    addDevices(other.devList, other.isMiffyList);

    final mergedKeys = deviceMap.keys.toList();
    final mergedDevList = mergedKeys
        .map((key) => deviceMap[key]!)
        .toList(growable: false);
    final mergedIsMiffy = mergedKeys
        .map((key) => miffyMap[key] ?? false)
        .toList(growable: false);

    final mergedClouds = <DeviceRecipeCloud>[];
    for (final key in mergedKeys) {
      final cloud = deviceCloudMap.remove(key);
      if (cloud != null) {
        mergedClouds.add(cloud);
      }
    }
    if (deviceCloudMap.isNotEmpty) {
      mergedClouds.addAll(deviceCloudMap.values);
    }

    final adjustedIndex = mergedDevList.isEmpty
        ? 0
        : selectedIndex.clamp(0, mergedDevList.length - 1).toInt();

    return RecipeCloudListState(
      data: mergedClouds,
      devList: mergedDevList,
      selectedIndex: adjustedIndex,
      isMiffyList: mergedIsMiffy,
    );
  }

  DeviceRecipeCloud getDeviceRecipeCloud(String devId) {
    for (var model in data) {
      if (model.deviceId == devId) {
        return model;
      }
    }
    DeviceRecipeCloud model = DeviceRecipeCloud.initial();
    model.deviceId = devId;
    return model;
  }

  // 更新设备菜谱数据
  RecipeCloudListState updateDeviceRecipeCloud(DeviceRecipeCloud devCloud) {
    final newData = List<DeviceRecipeCloud>.from(data);
    bool found = false;

    for (int i = 0; i < newData.length; i++) {
      if (newData[i].deviceId == devCloud.deviceId) {
        newData[i] = devCloud;
        found = true;
        break;
      }
    }

    if (!found) {
      newData.add(devCloud);
    }

    return copyWith(data: newData);
  }

  // 添加设备到列表
  RecipeCloudListState addDevice(ThingSmartDeviceModel device) {
    final newDevList = List<ThingSmartDeviceModel>.from(devList);
    if (!newDevList.any((d) => d.devId == device.devId)) {
      newDevList.add(device);
    }
    return copyWith(devList: newDevList);
  }
}

class DeviceRecipeCloud {
  final List<RecipeCardData> data;
  String? deviceId;
  String? pid;
  int pageNum;
  int totalSize;

  DeviceRecipeCloud({
    required this.data,
    this.deviceId,
    this.pid,
    this.pageNum = 0,
    this.totalSize = 0,
  });

  factory DeviceRecipeCloud.initial() =>
      DeviceRecipeCloud(data: [], pageNum: 0, totalSize: 0);

  DeviceRecipeCloud copyWith({
    List<RecipeCardData>? data,
    String? deviceId,
    String? pid,
    int? pageNum,
    int? totalSize,
  }) {
    return DeviceRecipeCloud(
      data: data ?? List.from(this.data),
      deviceId: deviceId ?? this.deviceId,
      pid: pid ?? this.pid,
      pageNum: pageNum ?? this.pageNum,
      totalSize: totalSize ?? this.totalSize,
    );
  }
}
